<template>
  <div class="resume-edit-page">
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <div class="header-left">
          <el-button @click="goBack" plain>
            <el-icon><arrow-left /></el-icon>
            返回
          </el-button>
          <h1 class="page-title">{{ isEdit ? '编辑简历' : '创建简历' }}</h1>
        </div>
        <div class="header-right">
          <el-button 
            type="primary" 
            @click="saveResumeDirectly" 
            :loading="saving"
          >
            保存简历
          </el-button>
          <el-button 
            type="success" 
            @click="previewResume"
          >
            <el-icon><view /></el-icon>
            预览
          </el-button>
        </div>
      </div>

      <!-- 进度提示 -->
      <div class="progress-bar">
        <el-progress 
          :percentage="completionRate" 
          :format="percentFormat"
          :color="getCompletionColor(completionRate)"
        />
        <p class="progress-tip">完善的简历可以提高您的求职成功率</p>
      </div>

      <!-- 编辑区域 -->
      <div class="edit-container" v-loading="loading">
        <el-tabs v-model="activeTab" class="resume-tabs">
          <el-tab-pane name="basic">
            <template #label>
              <span class="tab-label">
                <el-icon><user /></el-icon>
                基本信息
              </span>
            </template>
            <resume-basic-form
              v-if="resumeData"
              :model-value="resumeData.basic"
              @update:model-value="updateBasicInfo"
            />
          </el-tab-pane>

          <el-tab-pane name="education">
            <template #label>
              <span class="tab-label">
                <el-icon><school /></el-icon>
                教育背景
              </span>
            </template>
            <resume-education-list
              v-if="resumeData"
              :model-value="resumeData.educations"
              @update:model-value="updateEducations"
            />
          </el-tab-pane>

          <el-tab-pane name="experience">
            <template #label>
              <span class="tab-label">
                <el-icon><office-building /></el-icon>
                工作经历
              </span>
            </template>
            <resume-experience-list
              v-if="resumeData"
              :model-value="resumeData.experiences"
              @update:model-value="updateExperiences"
            />
          </el-tab-pane>

          <el-tab-pane name="project">
            <template #label>
              <span class="tab-label">
                <el-icon><collection /></el-icon>
                项目经验
              </span>
            </template>
            <resume-project-list
              v-if="resumeData"
              :model-value="resumeData.projects"
              @update:model-value="updateProjects"
            />
          </el-tab-pane>

          <el-tab-pane name="skills">
            <template #label>
              <span class="tab-label">
                <el-icon><medal /></el-icon>
                技能证书
              </span>
            </template>
            <resume-skills-form
              v-if="resumeData"
              :model-value="resumeData.skills"
              @update:model-value="updateSkills"
            />
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 底部操作栏 -->
      <div class="bottom-actions">
        <div class="action-left">
          <el-button 
            v-if="activeTab !== firstTab" 
            @click="prevStep"
            plain
          >
            <el-icon><arrow-left /></el-icon>
            上一步
          </el-button>
        </div>
        <div class="action-right">
          <el-button 
            v-if="activeTab !== lastTab" 
            type="primary" 
            @click="nextStep"
          >
            下一步
            <el-icon><arrow-right /></el-icon>
          </el-button>
          <template v-else>
            <el-button type="success" @click="saveAndPreview">
              完成并预览
            </el-button>
          </template>
        </div>
      </div>
    </div>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="简历预览"
      width="900px"
      top="5vh"
      append-to-body
      center
      destroy-on-close
      :show-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      class="resume-preview-dialog"
    >
      <div class="resume-preview">
        <div class="preview-header">
          <h3 class="preview-title">{{ resumeData?.basic?.name || '我' }}的简历</h3>
          <p class="preview-subtitle">创建于 {{ formatCurrentDate() }}</p>
          
          <div class="preview-actions">
            <el-button type="primary" @click="downloadResume" size="large">
              <el-icon><download /></el-icon>
              下载 PDF 简历
            </el-button>
            <el-button @click="previewVisible = false" plain size="large">
              <el-icon><close /></el-icon>
              关闭预览
            </el-button>
          </div>
        </div>
        
        <div class="preview-container">
          <div class="paper-effect">
            <resume-preview-content :resume="resumeData" />
          </div>
        </div>
      </div>

      <template #footer>
        <div class="preview-footer">
          <p class="preview-tip">提示：您可以下载 PDF 格式简历或关闭预览继续编辑</p>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import {
  ArrowLeft,
  ArrowRight,
  User,
  School,
  OfficeBuilding,
  Collection,
  Medal,
  View,
  Download,
  Close
} from '@element-plus/icons-vue'
import { getResumeDetail, createResume, updateResume } from '@/api/resume'

// 组件引入
import ResumeBasicForm from '@/components/resume/ResumeBasicForm.vue'
import ResumeEducationList from '@/components/resume/ResumeEducationList.vue'
import ResumeExperienceList from '@/components/resume/ResumeExperienceList.vue'
import ResumeProjectList from '@/components/resume/ResumeProjectList.vue'
import ResumeSkillsForm from '@/components/resume/ResumeSkillsForm.vue'
import ResumePreviewContent from '@/components/resume/ResumePreviewContent.vue'

const route = useRoute()
const router = useRouter()

// 状态
const loading = ref(false)
const saving = ref(false)
const previewVisible = ref(false)
const activeTab = ref('basic')
const resumeData = ref(null)

// 计算属性
const isEdit = computed(() => {
  const hasId = !!route.params.id;
  console.log('当前路由参数ID:', route.params.id);
  console.log('是否为编辑模式:', hasId);
  return hasId;
})
const completionRate = computed(() => {
  if (!resumeData.value) return 0

  let totalFields = 0
  let completedFields = 0

  // 检查基本信息
  if (resumeData.value.basic) {
    const basicFields = ['name', 'phone', 'email', 'gender', 'title', 'location', 'birthday', 'experience']
    totalFields += basicFields.length
    completedFields += basicFields.filter(field => !!resumeData.value.basic[field]).length
  }

  // 检查教育经历
  if (Array.isArray(resumeData.value.educations)) {
    totalFields += 1 // 至少需要一条教育经历
    if (resumeData.value.educations.length > 0) {
      completedFields += 1
    }
  }

  // 检查工作经历
  if (Array.isArray(resumeData.value.experiences)) {
    totalFields += 1 // 至少需要一条工作经历
    if (resumeData.value.experiences.length > 0) {
      completedFields += 1
    }
  }

  // 检查项目经验
  if (Array.isArray(resumeData.value.projects)) {
    totalFields += 1 // 至少需要一条项目经验
    if (resumeData.value.projects.length > 0) {
      completedFields += 1
    }
  }

  // 检查技能
  if (resumeData.value.skills) {
    const skillFields = ['skillTags', 'certificates', 'languages']
    totalFields += skillFields.length
    completedFields += skillFields.filter(field => 
      Array.isArray(resumeData.value.skills[field]) && 
      resumeData.value.skills[field].length > 0
    ).length
  }

  // 计算完整度百分比
  return Math.round((completedFields / totalFields) * 100)
})

// 标签页配置
const tabs = ['basic', 'education', 'experience', 'project', 'skills']
const firstTab = tabs[0]
const lastTab = tabs[tabs.length - 1]

// 方法
const goBack = () => {
  try {
    // 先尝试返回上一页
    if (window.history.length > 1) {
      router.back()
    } else {
      // 如果没有历史记录，则返回首页
      router.push('/')
    }
  } catch (e) {
    console.error('导航失败:', e)
    // 导航失败时，尝试回到首页
    router.push('/')
  }
}

const percentFormat = (percentage) => {
  return percentage + '%'
}

const getCompletionColor = (percentage) => {
  if (percentage < 40) return '#F56C6C'
  if (percentage < 70) return '#E6A23C'
  return '#67C23A'
}

const fetchResumeData = async () => {
  loading.value = true
  try {
    if (isEdit.value) {
      // 获取简历详情
      const response = await getResumeDetail(route.params.id)
      if (response && response.code === 200) {
        // 将后端数据转换为表单数据结构
        const data = response.data;
        
        // 解析职业期望
        const jobExpectationData = parseJobExpectation(data.jobExpectation);
        
        // 解析工作经历
        const parsedExperiences = parseExperiences(data.workExperience);
        
        // 解析项目经历
        const parsedProjects = parseProjects(data.projectExperience);
        
        // 解析技能和证书
        const skillsData = {
          skillTags: data.skills ? data.skills.split(',').map(s => s.trim()) : [],
          certificates: data.certificates ? data.certificates.split(',').map(c => c.trim()) : [],
          languages: data.languages ? data.languages.split(',').map(l => l.trim()) : []
        };
        
        // 构建教育信息
        const educationsData = [{
          school: data.school,
          major: data.major,
          degree: data.education,
          graduationYear: data.graduationYear,
          startDate: data.schoolStartDate || '',
          endDate: data.schoolEndDate || '',
          description: data.schoolExperience || ''
        }];
        
        // 构建基本信息
        const basicData = {
          name: data.name,
          phone: data.phone,
          email: data.email,
          gender: data.gender,
          selfIntroduction: data.selfEvaluation,
          title: data.title || '我的简历',
          location: data.location || '',
          birthday: data.birthday || '',
          experience: data.workYears || '',
          ...jobExpectationData
        };
        
        // 使用nextTick更新resumeData
        await nextTick();
        
        // 创建完整的新数据对象
        const newResumeData = {
          id: data.id,
          name: data.name,
          phone: data.phone,
          email: data.email,
          age: data.age,
          gender: data.gender,
          education: data.education,
          school: data.school,
          major: data.major,
          graduationYear: data.graduationYear,
          workExperience: data.workExperience,
          projectExperience: data.projectExperience,
          skills: data.skills,
          certificates: data.certificates,
          selfEvaluation: data.selfEvaluation,
          status: data.status,
          isDefault: data.isDefault,
          
          title: data.title,
          location: data.location,
          birthday: data.birthday,
          workYears: data.workYears,
          jobExpectation: data.jobExpectation,
          schoolStartDate: data.schoolStartDate,
          schoolEndDate: data.schoolEndDate,
          schoolExperience: data.schoolExperience,
          
          // 使用解析后的数据
          basic: basicData,
          educations: educationsData,
          experiences: parsedExperiences,
          projects: parsedProjects,
          skills: skillsData
        };
        
        // 再次使用nextTick更新resumeData
        await nextTick();
        resumeData.value = newResumeData;
      } else {
        ElMessage.error(response?.message || '获取简历数据失败')
      }
    } else {
      // 创建新简历时的默认数据
      const defaultResumeData = {
        name: '',
        phone: '',
        email: '',
        age: null,
        gender: '',
        education: '',
        school: '',
        major: '',
        graduationYear: null,
        workExperience: '',
        projectExperience: '',
        skills: '',
        certificates: '',
        selfEvaluation: '',
        status: 0,
        isDefault: false,
        
        // 前端表单所需数据结构
        basic: {
          name: '',
          phone: '',
          email: '',
          gender: '',
          selfIntroduction: '',
          title: '我的简历',
          location: '',
          birthday: '',
          experience: '',
          currentStatus: '',
          expectSalary: '',
          expectLocation: ''
        },
        educations: [],
        experiences: [],
        projects: [],
        skills: {
          skillTags: [],
          certificates: [],
          languages: []
        }
      };
      
      await nextTick();
      resumeData.value = defaultResumeData;
    }
  } catch (error) {
    console.error('获取简历数据失败', error)
    ElMessage.error('获取简历数据失败')
  } finally {
    loading.value = false
  }
}

// 修改解析工作经历的函数
const parseExperiences = (experienceText) => {
  if (!experienceText) return [];
  
  const experiences = [];
  const expBlocks = experienceText.split('\n\n');
  
  expBlocks.forEach((block, index) => {
    try {
      // 尝试解析JSON格式
      const expData = JSON.parse(block);
      experiences.push({
        id: index + 1,
        company: expData.company || '',
        position: expData.position || '',
        startDate: expData.startDate || '',
        endDate: expData.endDate || '至今',
        description: expData.description || ''
      });
    } catch (e) {
      // 如果JSON解析失败，尝试解析旧格式
      const lines = block.split('\n');
      if (lines.length > 0) {
        const headerParts = lines[0].split('-');
        if (headerParts.length >= 3) {
          const [company, position, dateRange] = headerParts;
          const dateParts = dateRange.split('至');
          const description = lines.slice(1).join('\n');
          
          experiences.push({
            id: index + 1,
            company: company.trim(),
            position: position.trim(),
            startDate: dateParts[0]?.trim() || '',
            endDate: dateParts[1]?.trim() || '至今',
            description: description
          });
        }
      }
    }
  });
  
  return experiences;
};

// 修改解析项目经历的函数
const parseProjects = (projectText) => {
  if (!projectText) return [];
  
  const projects = [];
  const projBlocks = projectText.split('\n\n');
  
  projBlocks.forEach((block, index) => {
    try {
      // 尝试解析JSON格式
      const projData = JSON.parse(block);
      projects.push({
        id: index + 1,
        name: projData.name || '',
        role: projData.role || '',
        startDate: projData.startDate || '',
        endDate: projData.endDate || '至今',
        description: projData.description || ''
      });
    } catch (e) {
      // 如果JSON解析失败，尝试解析旧格式
      const lines = block.split('\n');
      if (lines.length > 0) {
        const headerParts = lines[0].split('-');
        if (headerParts.length >= 3) {
          const [name, role, dateRange] = headerParts;
          const dateParts = dateRange.split('至');
          const description = lines.slice(1).join('\n');
          
          projects.push({
            id: index + 1,
            name: name.trim(),
            role: role.trim(),
            startDate: dateParts[0]?.trim() || '',
            endDate: dateParts[1]?.trim() || '至今',
            description: description
          });
        }
      }
    }
  });
  
  return projects;
};

// 解析职业期望
const parseJobExpectation = (jobExpectationStr) => {
  if (!jobExpectationStr) {
    return {
      currentStatus: '',
      expectSalary: '',
      expectLocation: ''
    };
  }
  
  try {
    const expectation = JSON.parse(jobExpectationStr);
    return {
      currentStatus: expectation.status || '',
      expectSalary: expectation.salary || '',
      expectLocation: expectation.location || ''
    };
  } catch (error) {
    console.error('解析职业期望数据失败', error);
    return {
      currentStatus: '',
      expectSalary: '',
      expectLocation: ''
    };
  }
};

// 确保日期格式的辅助函数
const formatDateField = (dateStr) => {
  if (!dateStr) return '';
  
  // 如果是"至今"，直接返回
  if (dateStr === '至今' || dateStr === '进行中') {
    return dateStr;
  }

  try {
    // 处理 YYYY-MM-DD 格式
    if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
      return dateStr;
    }

    // 处理 YYYY-M-D 格式
    if (/^\d{4}-\d{1,2}-\d{1,2}$/.test(dateStr)) {
      const [year, month, day] = dateStr.split('-');
      return `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`;
    }

    // 处理 YYYY-MM 格式
    if (/^\d{4}-\d{1,2}$/.test(dateStr)) {
      const [year, month] = dateStr.split('-');
      return `${year}-${month.padStart(2, '0')}-01`;
    }

    // 处理纯年份
    if (/^\d{4}$/.test(dateStr)) {
      return `${dateStr}-01-01`;
    }

    // 处理中文日期格式
    const chineseMatch = dateStr.match(/^(\d{4})年(\d{1,2})月(?:(\d{1,2})日)?$/);
    if (chineseMatch) {
      const [, year, month, day] = chineseMatch;
      return `${year}-${month.padStart(2, '0')}-${(day || '1').padStart(2, '0')}`;
    }

    // 尝试用Date对象解析
    const date = new Date(dateStr);
    if (!isNaN(date.getTime())) {
      return date.toISOString().split('T')[0];
    }

    console.warn('无法识别的日期格式:', dateStr);
    return '';
  } catch (e) {
    console.error('日期格式化错误:', e);
    return '';
  }
};

// 更新方法
const updateBasicInfo = async (value) => {
  await nextTick()
  resumeData.value = {
    ...resumeData.value,
    basic: { ...value }
  }
}

const updateEducations = async (value) => {
  await nextTick()
  resumeData.value = {
    ...resumeData.value,
    educations: [...value]
  }
}

const updateExperiences = async (value) => {
  await nextTick()
  resumeData.value = {
    ...resumeData.value,
    experiences: [...value]
  }
}

const updateProjects = async (value) => {
  await nextTick()
  resumeData.value = {
    ...resumeData.value,
    projects: [...value]
  }
}

const updateSkills = async (value) => {
  await nextTick()
  resumeData.value = {
    ...resumeData.value,
    skills: { ...value }
  }
}

// 保存简历
const saveResume = async () => {
  console.log('[DEBUG] saveResume方法被调用');
  console.log('开始保存简历...');
  console.log('当前简历ID:', route.params.id);
  console.log('编辑模式:', isEdit.value);
  
  // 防止重复保存
  if (saving.value) {
    console.log('[DEBUG] 已经在保存中，忽略重复请求');
    return;
  }
  
  saving.value = true
  
  try {
    if (!isEdit.value && !route.params.id) {
      console.log('[DEBUG] 创建模式，但无ID');
    } else {
      console.log('[DEBUG] 确认更新模式，ID存在:', route.params.id);
    }
    
    // 处理数据，将我们的表单数据转换为API所需的格式
    const apiData = {
      name: resumeData.value.basic?.name || '',
      phone: resumeData.value.basic?.phone || '',
      email: resumeData.value.basic?.email || '',
      age: resumeData.value.basic?.age || 0,
      gender: resumeData.value.basic?.gender || '',
      education: resumeData.value.educations?.[0]?.degree || '',
      school: resumeData.value.educations?.[0]?.school || '',
      major: resumeData.value.educations?.[0]?.major || '',
      graduationYear: resumeData.value.educations?.[0]?.graduationYear || 0,
      workExperience: resumeData.value.experiences?.map(exp => {
        console.log('[URGENT] 处理工作经历日期:', exp.startDate, exp.endDate);
        let startDateFormatted = formatDateField(exp.startDate);
        let endDateFormatted = exp.endDate === '至今' ? exp.endDate : formatDateField(exp.endDate);
        console.log('[URGENT] 格式化后的工作经历日期:', startDateFormatted, endDateFormatted);
        return `${exp.company}-${exp.position}-${startDateFormatted || ''}至${endDateFormatted || '至今'}\n${exp.description}`;
      }).join('\n\n') || '',
      projectExperience: resumeData.value.projects?.map(proj => {
        console.log('[URGENT] 处理项目经历日期:', proj.startDate, proj.endDate);
        let startDateFormatted = formatDateField(proj.startDate);
        let endDateFormatted = proj.endDate === '至今' ? proj.endDate : formatDateField(proj.endDate);
        console.log('[URGENT] 格式化后的项目经历日期:', startDateFormatted, endDateFormatted);
        return `${proj.name}-${proj.role}-${startDateFormatted || ''}至${endDateFormatted || '至今'}\n${proj.description}`;
      }).join('\n\n') || '',
      // 确保skills字段是字符串类型
      skills: typeof resumeData.value.skills === 'string' 
        ? resumeData.value.skills
        : (Array.isArray(resumeData.value.skills?.skillTags) 
            ? resumeData.value.skills.skillTags.join(', ') 
            : ''),
      // 确保certificates字段是字符串类型
      certificates: Array.isArray(resumeData.value.skills?.certificates)
        ? resumeData.value.skills.certificates.join(', ')
        : (typeof resumeData.value.certificates === 'string'
            ? resumeData.value.certificates
            : ''),
      // 添加语言能力字段
      languages: Array.isArray(resumeData.value.skills?.languages)
        ? resumeData.value.skills.languages.join(', ')
        : '',
      selfEvaluation: resumeData.value.basic?.selfIntroduction || '',
      status: resumeData.value.status || 0,
      isDefault: resumeData.value.isDefault || false,
      
      // 新增字段 - 确保都是字符串类型
      title: resumeData.value.basic?.title || '我的简历',
      location: resumeData.value.basic?.location || '',
      birthday: formatDateField(resumeData.value.basic?.birthday) || '',
      workYears: resumeData.value.basic?.experience || '',
      jobExpectation: typeof resumeData.value.basic?.jobExpectation === 'string'
        ? resumeData.value.basic.jobExpectation
        : JSON.stringify({
            salary: resumeData.value.basic?.expectSalary || '',
            location: resumeData.value.basic?.expectLocation || '',
            status: resumeData.value.basic?.currentStatus || ''
          }),
      schoolStartDate: formatDateField(resumeData.value.educations?.[0]?.startDate) || '',
      schoolEndDate: formatDateField(resumeData.value.educations?.[0]?.endDate) || '',
      schoolExperience: resumeData.value.educations?.[0]?.description || ''
    };
    
    // 确保字段不为null
    Object.keys(apiData).forEach(key => {
      if (apiData[key] === null) {
        if (key === 'age' || key === 'graduationYear') {
          apiData[key] = 0; // 数字类型字段设为0
        } else if (key === 'isDefault') {
          apiData[key] = false; // 布尔类型字段设为false
        } else {
          apiData[key] = ''; // 字符串类型字段设为空字符串
        }
      }
    });
    
    console.log('[DEBUG] 准备保存简历数据:', JSON.stringify(apiData, null, 2));
    console.log('[DEBUG] 工作经历数据:', JSON.stringify(resumeData.value.experiences, null, 2));
    console.log('[DEBUG] 教育经历数据:', JSON.stringify(resumeData.value.educations, null, 2));
    
    let response;
    
    if (isEdit.value) {
      // 更新现有简历
      console.log(`[DEBUG] 调用updateResume API，ID: ${route.params.id}`);
      
      try {
        // 使用原生XMLHttpRequest作为最后的备选项
        await new Promise((resolve, reject) => {
          console.log('[DEBUG] 使用原生XMLHttpRequest发送请求');
          const xhr = new XMLHttpRequest();
          xhr.open('PUT', `http://localhost:8080/api/resumes/${route.params.id}`, true);
          xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
          const token = localStorage.getItem('token');
          if (token) {
            xhr.setRequestHeader('Authorization', `Bearer ${token}`);
          }
          xhr.withCredentials = true;
          
          xhr.onload = function() {
            if (xhr.status >= 200 && xhr.status < 300) {
              console.log('[DEBUG] XMLHttpRequest响应成功:', xhr.responseText);
              try {
                const jsonResponse = JSON.parse(xhr.responseText);
                if (jsonResponse.code === 200) {
                  console.log('[DEBUG] 请求成功，业务状态码正确');
                  resolve(jsonResponse);
                } else {
                  console.error('[DEBUG] 请求成功，但业务状态码错误:', jsonResponse.code, jsonResponse.message);
                  reject(new Error(jsonResponse.message || '业务错误'));
                }
              } catch (e) {
                console.error('[DEBUG] 解析响应JSON出错:', e);
                // 即使解析错误，也当作成功处理，以确保页面不会卡死
                resolve({ code: 200, message: '请求成功但响应格式异常' });
              }
            } else {
              // 尝试解析错误响应
              console.error('[DEBUG] XMLHttpRequest请求失败，状态码:', xhr.status);
              let errorMessage = `请求失败: ${xhr.status}`;
              try {
                const errorResponse = JSON.parse(xhr.responseText);
                if (errorResponse.message) {
                  errorMessage = errorResponse.message;
                }
              } catch (e) {
                // 忽略解析错误
              }
              reject(new Error(errorMessage));
            }
          };
          
          xhr.onerror = function() {
            console.error('[DEBUG] XMLHttpRequest请求遇到网络错误');
            reject(new Error('网络请求失败，可能是CORS或网络连接问题'));
          };
          
          xhr.ontimeout = function() {
            console.error('[DEBUG] XMLHttpRequest请求超时');
            reject(new Error('请求超时，服务器响应时间过长'));
          };
          
          // 设置超时时间
          xhr.timeout = 30000; // 30秒
          
          const jsonData = JSON.stringify(apiData);
          console.log('[DEBUG] 发送数据:', jsonData);
          xhr.send(jsonData);
        });
        
        console.log('[DEBUG] XMLHttpRequest请求完成');
        response = { code: 200, message: '操作成功' };
      } catch (xhrError) {
        console.error('[DEBUG] XMLHttpRequest请求出错:', xhrError);
        throw xhrError;
      }
      
      // 备用方案1：使用正常的API调用
      try {
        console.log('[DEBUG] 尝试正常API调用更新简历');
        const normalResponse = await updateResume(route.params.id, apiData);
        console.log('[DEBUG] 正常API调用响应:', normalResponse);
      } catch (normalError) {
        console.error('[DEBUG] 正常API调用失败:', normalError);
      }
    } else {
      // 创建新简历
      console.log('[DEBUG] 调用createResume API');
      response = await createResume(apiData)
      console.log('[DEBUG] createResume API调用完成，响应:', response);
    }
    
    console.log('[DEBUG] 保存简历响应:', response);
    
    if (response && response.code === 200) {
      console.log('[DEBUG] 保存成功，显示成功消息');
    ElMessage.success('简历保存成功')
      
      if (!isEdit.value && response.data) {
      // 创建成功后跳转到编辑页
        console.log('[DEBUG] 新建模式，跳转到编辑页');
        router.replace(`/resumes/${response.data.id}/edit`)
      }
      
      // 刷新简历数据，确保显示最新状态
      if (isEdit.value) {
        console.log('[DEBUG] 编辑模式，刷新简历数据');
        await fetchResumeData();
      }
    } else {
      console.error('[DEBUG] 保存失败，错误信息:', response?.message);
      ElMessage.error(response?.message || '保存简历失败')
    }
  } catch (error) {
    console.error('[DEBUG] 保存简历异常:', error)
    ElMessage.error('保存简历失败，请稍后再试')
  } finally {
    saving.value = false
  }
}

// 预览简历
const previewResume = () => {
  previewVisible.value = true
}

// 下载简历
const downloadResume = () => {
  ElMessage.success('简历下载已开始')
  // 实际实现应调用后端API进行PDF生成和下载
}

// 保存并预览
const saveAndPreview = async () => {
  await saveResumeDirectly()
  previewResume()
}

// 步骤导航
const prevStep = () => {
  const currentIndex = tabs.indexOf(activeTab.value)
  if (currentIndex > 0) {
    activeTab.value = tabs[currentIndex - 1]
  }
}

const nextStep = () => {
  const currentIndex = tabs.indexOf(activeTab.value)
  if (currentIndex < tabs.length - 1) {
    activeTab.value = tabs[currentIndex + 1]
  }
}

// 修改saveResumeDirectly方法中的工作经历和项目经历处理部分
const saveResumeDirectly = async () => {
  console.log('[URGENT] 开始直接保存简历');
  saving.value = true;
  
  try {
    let basicResumeData = {
      id: route.params.id,
      userId: null, // 后端会从token中获取
      name: resumeData.value.basic?.name || '',
      phone: resumeData.value.basic?.phone || '',
      email: resumeData.value.basic?.email || '',
      gender: resumeData.value.basic?.gender || '',
      title: resumeData.value.basic?.title || '我的简历',
      location: resumeData.value.basic?.location || '',
      birthday: formatDateField(resumeData.value.basic?.birthday) || '',
      workYears: resumeData.value.basic?.experience || '',
      education: resumeData.value.educations?.[0]?.degree || '',
      school: resumeData.value.educations?.[0]?.school || '',
      major: resumeData.value.educations?.[0]?.major || '',
      graduationYear: resumeData.value.educations?.[0]?.graduationYear || 0,
      schoolStartDate: formatDateField(resumeData.value.educations?.[0]?.startDate) || '',
      schoolEndDate: formatDateField(resumeData.value.educations?.[0]?.endDate) || '',
      schoolExperience: resumeData.value.educations?.[0]?.description || '',
      
      // 修改工作经历的处理 - 使用JSON格式保存
      workExperience: resumeData.value.experiences?.map(exp => {
        // 格式化日期
        const startDate = formatDateField(exp.startDate);
        const endDate = exp.endDate === '至今' ? exp.endDate : formatDateField(exp.endDate);
        
        // 创建工作经历对象
        const experienceObj = {
          company: exp.company,
          position: exp.position,
          startDate: startDate,
          endDate: endDate,
          description: exp.description
        };
        
        // 转换为JSON字符串
        return JSON.stringify(experienceObj);
      }).join('\n\n') || '',
      
      // 修改项目经历的处理 - 使用JSON格式保存
      projectExperience: resumeData.value.projects?.map(proj => {
        // 格式化日期
        const startDate = formatDateField(proj.startDate);
        const endDate = proj.endDate === '至今' ? proj.endDate : formatDateField(proj.endDate);
        
        // 创建项目经历对象
        const projectObj = {
          name: proj.name,
          role: proj.role,
          startDate: startDate,
          endDate: endDate,
          description: proj.description
        };
        
        // 转换为JSON字符串
        return JSON.stringify(projectObj);
      }).join('\n\n') || '',
      
      skills: Array.isArray(resumeData.value.skills?.skillTags) 
        ? resumeData.value.skills.skillTags.join(', ') : '',
      
      certificates: Array.isArray(resumeData.value.skills?.certificates)
        ? resumeData.value.skills.certificates.join(', ') : '',
      
      languages: Array.isArray(resumeData.value.skills?.languages)
        ? resumeData.value.skills.languages.join(', ') : '',
      
      selfEvaluation: resumeData.value.basic?.selfIntroduction || '',
      
      jobExpectation: JSON.stringify({
        salary: resumeData.value.basic?.expectSalary || '',
        location: resumeData.value.basic?.expectLocation || '',
        status: resumeData.value.basic?.currentStatus || ''
      }),
      
      status: 0,
      isDefault: false
    };
    
    // 确保没有null值
    Object.keys(basicResumeData).forEach(key => {
      if (basicResumeData[key] === null) {
        if (key === 'graduationYear') {
          basicResumeData[key] = 0;
        } else if (key === 'isDefault') {
          basicResumeData[key] = false;
        } else if (key !== 'userId') { // userId可以保持为null
          basicResumeData[key] = '';
        }
      }
    });
    
    // 输出完整请求数据便于调试
    console.log('[URGENT] 准备发送的简历数据:', JSON.stringify(basicResumeData, null, 2));
    
    // 常规Axios请求
    console.log('[URGENT] 使用Axios尝试保存简历');
    
    // 获取token并构建授权头
    const axiosToken = localStorage.getItem('token') || '';
    console.log('[URGENT] 使用的授权令牌:', axiosToken ? '有效' : '无效');
    
    const response = await axios.put(
      `http://localhost:8080/api/resumes/${route.params.id}`,
      basicResumeData,
      {
        headers: {
          'Content-Type': 'application/json',
          'X-Requested-With': 'XMLHttpRequest',
          'Authorization': axiosToken ? `Bearer ${axiosToken}` : ''
        },
        timeout: 10000, // 10秒超时
        withCredentials: true // 包含cookies
      }
    );
    
    console.log('[URGENT] 保存简历成功 (Axios):', response);
    console.log('[URGENT] 响应数据:', JSON.stringify(response.data, null, 2));
    ElMessage.success('简历保存成功!');
    
    // 使用nextTick来更新resumeData
    if (response.data && response.data.data) {
      const data = response.data.data;
      await nextTick();
      // 创建一个新的对象来存储更新后的数据
      const newResumeData = {
        id: data.id,
        name: data.name,
        phone: data.phone,
        email: data.email,
        gender: data.gender,
        title: data.title || '我的简历',
        location: data.location || '',
        birthday: data.birthday || '',
        workYears: data.workYears || '',
        education: data.education || '',
        school: data.school || '',
        major: data.major || '',
        graduationYear: data.graduationYear || 0,
        schoolStartDate: data.schoolStartDate || '',
        schoolEndDate: data.schoolEndDate || '',
        schoolExperience: data.schoolExperience || '',
        // 保持其他字段不变
        basic: { ...resumeData.value.basic },
        educations: [...resumeData.value.educations],
        experiences: [...resumeData.value.experiences],
        projects: [...resumeData.value.projects],
        skills: { ...resumeData.value.skills }
      };
      
      // 在下一个tick更新resumeData
      await nextTick();
      resumeData.value = newResumeData;
    }
    
    return;
  } catch (error) {
    console.error('[URGENT] Axios保存简历失败:', error);
    
    // 记录完整错误信息
    if (error.response) {
      console.error('[URGENT] 服务器响应状态码:', error.response.status);
      console.error('[URGENT] 服务器响应数据:', JSON.stringify(error.response.data, null, 2));
      // 显示错误消息
      ElMessage.error(`保存失败: 服务器返回 ${error.response.status} 错误`);
    } else if (error.request) {
      // 请求已发出但没有收到响应
      console.error('[URGENT] 请求已发送但无响应:', error.request);
      ElMessage.error('保存失败: 服务器没有响应');
    } else {
      // 在设置请求时出错
      console.error('[URGENT] 请求设置错误:', error.message);
      ElMessage.error(`保存失败: ${error.message}`);
    }
  } finally {
    saving.value = false; // 无论成功或失败，都重置保存状态
  }
};

// 添加格式化当前日期的方法
const formatCurrentDate = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 初始化
onMounted(() => {
  fetchResumeData()
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.css';

.resume-edit-page {
  background-color: var(--color-background);
  min-height: calc(100vh - 70px);
  padding: var(--spacing-xl) 0;

  .container {
    max-width: var(--container-max-width);
    margin: 0 auto;
    padding: 0 var(--spacing-lg);
  }

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: var(--spacing-lg);

    .header-left {
      display: flex;
      align-items: center;
      gap: var(--spacing-md);
      
      .page-title {
        font-size: var(--font-size-xl);
        font-weight: 600;
        color: var(--text-primary);
        margin: 0;
      }
    }
    
    .header-right {
      display: flex;
      gap: var(--spacing-sm);
    }
  }
  
  .progress-bar {
    margin-bottom: var(--spacing-xl);
    
    .progress-tip {
      margin-top: var(--spacing-xs);
      color: var(--text-secondary);
      font-size: var(--font-size-sm);
    }
  }
  
  .edit-container {
    background-color: var(--color-white);
    border-radius: var(--border-radius-lg);
    box-shadow: var(--box-shadow);
    padding: var(--spacing-lg);
    margin-bottom: var(--spacing-xl);
    
    .resume-tabs {
      :deep(.el-tabs__nav) {
        border-radius: var(--border-radius-lg);
      }
      
      .tab-label {
        display: flex;
        align-items: center;
        gap: var(--spacing-xs);
        
        .el-icon {
          font-size: var(--font-size-lg);
        }
      }
    }
  }
  
  .bottom-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: var(--spacing-md) 0;
    
    .action-left,
    .action-right {
      display: flex;
      gap: var(--spacing-sm);
    }
  }
}

// 预览对话框
.resume-preview-dialog {
  :deep(.el-dialog__header) {
    padding: var(--spacing-lg);
    border-bottom: 1px solid var(--border-color-light);
    
    .el-dialog__title {
      font-size: var(--font-size-xl);
      font-weight: 600;
      color: var(--text-primary);
    }
  }
  
  :deep(.el-dialog__body) {
    padding: 0;
  }
  
  :deep(.el-dialog__footer) {
    padding: var(--spacing-md);
    border-top: 1px solid var(--border-color-light);
    background-color: var(--color-background-light);
  }
}

.resume-preview {
  .preview-header {
    background-color: var(--color-primary-light);
    padding: var(--spacing-lg);
    border-bottom: 1px solid var(--border-color-light);
    text-align: center;
    
    .preview-title {
      font-size: var(--font-size-xl);
      font-weight: 600;
      color: var(--color-primary);
      margin: 0 0 var(--spacing-xs);
    }
    
    .preview-subtitle {
      color: var(--text-secondary);
      margin: 0 0 var(--spacing-md);
      font-size: var(--font-size-sm);
    }
    
    .preview-actions {
      display: flex;
      justify-content: center;
      gap: var(--spacing-md);
      margin-top: var(--spacing-md);
    }
  }
  
  .preview-container {
    padding: var(--spacing-lg);
    background: linear-gradient(to right, #f5f7fa, #f1f4f9);
    max-height: 65vh;
    overflow-y: auto;
    
    &::-webkit-scrollbar {
      width: 8px;
    }
    
    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 4px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #ccc;
      border-radius: 4px;
    }
    
    &::-webkit-scrollbar-thumb:hover {
      background: #aaa;
    }
    
    .paper-effect {
      background-color: white;
      border-radius: var(--border-radius-lg);
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      padding: var(--spacing-xl);
      max-width: 780px;
      margin: 0 auto;
      position: relative;
      
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: var(--color-primary);
        border-radius: var(--border-radius-lg) var(--border-radius-lg) 0 0;
      }
    }
  }
  
  .preview-footer {
    text-align: center;
    
    .preview-tip {
      color: var(--text-secondary);
      font-size: var(--font-size-sm);
      margin: 0;
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .resume-edit-page {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: var(--spacing-md);
      
      .header-right {
        width: 100%;
        justify-content: flex-end;
      }
    }
  }
}
</style> 